package com.ddl.service.impl;

import com.ddl.common.enums.ErrorCode;
import com.ddl.common.exception.BusinessException;
import com.ddl.common.exception.ExceptionUtil;
import com.ddl.common.exception.ResultModel;
import com.ddl.dao.StagePropertyMapper;
import com.ddl.dao.UserFieldMapper;
import com.ddl.dao.UserMapper;
import com.ddl.dao.UserStagePropertyMapper;
import com.ddl.enums.StagePropertyTypeEnum;
import com.ddl.pojo.StageProperty;
import com.ddl.pojo.User;
import com.ddl.pojo.UserField;
import com.ddl.pojo.UserStageProperty;
import com.ddl.service.IUserFieldService;
import com.ddl.service.MoneyRecordService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.ddl.enums.StagePropertyTypeEnum.PU_TAO_ZHONG_ZI;

/**
 * @author dudianbo
 * @ClassName: ${CLASSNAME}
 * @Description: ${DESCRIPTION}
 * @date 2018/11/17
 */
@Service
public class UserFieldServiceImpl implements IUserFieldService {

    private final static Logger logger = LoggerFactory.getLogger(UserFieldServiceImpl.class);

    @Autowired
    UserFieldMapper userFieldMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    StagePropertyMapper stagePropertyMapper;

    @Autowired
    UserStagePropertyMapper userStagePropertyMapper;

    @Autowired
    MoneyRecordService moneyRecordService;


    @Override
    public ResultModel userField(String userId) {
        logger.info("用户田地入参userId={}", userId);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        Map<String, Object> map = new HashMap<>();
        try {
            User user = userMapper.selectByPrimaryKey(Integer.parseInt(userId));
            UserField record = new UserField();
            record.setUserId(Integer.parseInt(userId));
            record.setStatus(0);
            List<UserField> userFields = userFieldMapper.selectByRecord(record);
            List<UserStageProperty> stageProperties = userStagePropertyMapper.selectDogByUserId(Integer.parseInt(userId));
            Integer flag = 1;
            if (stageProperties == null || stageProperties.size() == 0) {
                flag = 0;
            }
            map.put("userName", user.getUserName());
            map.put("phone", user.getPhone());
            map.put("sex", user.getSex());
            map.put("growthValue", user.getGrowthValue());
            map.put("botanyList", userFields);
            map.put("imageUrl", user.getHeadImage());
            map.put("gold", user.getTotalAmount().intValue());
            map.put("isHaveDog", flag);
            resultModel.setData(map);
        } catch (Exception e) {
            logger.error("用户田地出现异常{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    @Override
    public ResultModel speciesField(String userId) {
        logger.info("种田地入参userId={}", userId);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        UserField record = new UserField();
        record.setUserId(Integer.parseInt(userId));
        record.setStatus(0);
        List<UserField> userFields = userFieldMapper.selectByRecord(record);
        StageProperty stageProperty = stagePropertyMapper.selectByType(PU_TAO_ZHONG_ZI.getType());
        UserStageProperty userStageProperty = new UserStageProperty();
        userStageProperty.setUserId(Integer.parseInt(userId));
        userStageProperty.setStagePropertyId(stageProperty.getId());
        List<UserStageProperty> list = userStagePropertyMapper.selectByRecord(userStageProperty);
        if (list == null || list.size() <= 0) {
            throw new BusinessException(ErrorCode.ACCOUNT_ERROR_311);
        }
        UserStageProperty update = list.get(0);
        if (userFields != null && userFields.size() >= 9) {
            //修改道具种子个数
            update.setCount(update.getCount() + 1);
            userStagePropertyMapper.updateByPrimaryKeySelective(update);
            throw new BusinessException(ErrorCode.ACCOUNT_ERROR_305);
        }
        record.setSeedType(0);
        record.setGold(new BigDecimal("5"));
        userFieldMapper.insertSelective(record);
        return resultModel;
    }

    @Override
    @Transactional
    public ResultModel stealingGold(String userId, Integer seedId) {
        logger.info("偷田地入参userId={}，seedId={}", userId, seedId);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            UserField userField = userFieldMapper.selectByPrimaryKey(seedId);
            if (userField.getSeedType() != 3) {
                throw new BusinessException(ErrorCode.BUSSINESS_ERROR_210);
            }
            //用户收自己田地
            if (userField.getUserId().toString().equals(userId)) {
                //修改田地状态
                UserField record = new UserField();
                record.setId(userField.getId());
                record.setStatus(1);
                record.setGold(BigDecimal.ZERO);
                record.setRemark("田地已收割");
                userFieldMapper.updateByPrimaryKeySelective(record);
                //增加自己金币金额
                User user = userMapper.selectByPrimaryKey(Integer.parseInt(userId));
                user.setTotalAmount(user.getTotalAmount().add(userField.getGold()));
                userMapper.updateByPrimaryKey(user);
                moneyRecordService.proveder(Integer.parseInt(userId), userField.getGold(), "收割自己田地收入");
            } else {
                //用户偷别人田地
                //金额不小于最低值
                if (userField.getGold() != null && userField.getGold().compareTo(new BigDecimal("2")) <= 0) {
                    throw new BusinessException(ErrorCode.ACCOUNT_ERROR_308);
                }
                //修改田地金币数
                UserField record = new UserField();
                record.setId(userField.getId());
                record.setGold(userField.getGold().subtract(new BigDecimal("1")));
                record.setRemark(userId + "偷走金币");
                userFieldMapper.updateByPrimaryKeySelective(record);
                //增加自己金币金额
                User user = userMapper.selectByPrimaryKey(Integer.parseInt(userId));
                user.setTotalAmount(user.getTotalAmount().add(new BigDecimal("1")));
                moneyRecordService.proveder(Integer.parseInt(userId), new BigDecimal("1"), "收割别人田地收入");
            }
        } catch (Exception e) {
            logger.error("用户偷田地出现异常{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    @Override
    @Transactional
    public ResultModel useStage(String userId, String type,String friendId) {
        logger.info("使用道具入参userId={}，type={}", userId, type);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            StageProperty stageProperty = stagePropertyMapper.selectByType(type);
            if (stageProperty == null) {
                throw new BusinessException(ErrorCode.ACCOUNT_ERROR_312);
            }
            UserStageProperty userStageProperty = new UserStageProperty();
            userStageProperty.setUserId(Integer.parseInt(userId));
            userStageProperty.setStagePropertyId(stageProperty.getId());
            List<UserStageProperty> list = userStagePropertyMapper.selectByRecord(userStageProperty);
            if (list == null || list.size() <= 0) {
                throw new BusinessException(ErrorCode.ACCOUNT_ERROR_311);
            }
            UserStageProperty update = list.get(0);
            if (update.getCount() <= 0) {
                if(StagePropertyTypeEnum.PU_TAO_ZHONG_ZI.getType().equalsIgnoreCase(stageProperty.getType())){
                    throw new BusinessException(ErrorCode.ACCOUNT_ERROR_311);
                }else{
                    throw new BusinessException(ErrorCode.ACCOUNT_ERROR_317);
                }
            }
            //修改道具个数
            update.setCount(update.getCount() - 1);
            userStagePropertyMapper.updateByPrimaryKeySelective(update);
            if(StagePropertyTypeEnum.DA_DOG_GUN.getType().equalsIgnoreCase(stageProperty.getType())){
                if(StringUtils.isNotBlank(friendId)) {
                    StageProperty DOG_HEAD = stagePropertyMapper.selectByType(StagePropertyTypeEnum.DOG_HEAD.getType());
                    StageProperty DOG = stagePropertyMapper.selectByType(StagePropertyTypeEnum.DOG.getType());
                    UserStageProperty record = new UserStageProperty();
                    record.setUserId(Integer.parseInt(friendId));
                    record.setStagePropertyId(DOG.getId());
                    List<UserStageProperty> dogs = userStagePropertyMapper.selectByRecord(record);
                    if (dogs != null) {
                        UserStageProperty dog = dogs.get(0);
                        if (dog.getCount() > 0) {
                            throw new BusinessException(ErrorCode.ACCOUNT_ERROR_318);
                        }
                    }
                    UserStageProperty twoRecord = new UserStageProperty();
                    twoRecord.setUserId(Integer.parseInt(friendId));
                    twoRecord.setStagePropertyId(DOG_HEAD.getId());
                    List<UserStageProperty> dogHeads = userStagePropertyMapper.selectByRecord(twoRecord);
                    if (dogHeads != null) {
                        UserStageProperty doghead = dogHeads.get(0);
                        if (doghead.getCount() > 0) {
                            Random rand = new Random();
                            int i = rand.nextInt(100); //int范围类的随机数
                            i=i%2;
                            if(i==0) {
                                throw new BusinessException(ErrorCode.ACCOUNT_ERROR_318);
                            }
                        }
                    }
                }
            }
            //如果道具是种子，就去种田地
            if (StagePropertyTypeEnum.PU_TAO_ZHONG_ZI.getType().equalsIgnoreCase(stageProperty.getType())) {
                speciesField(userId);
            }
        } catch (Exception e) {
            logger.error("使用道具出现异常{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }


    @Override
    public ResultModel beforeStealingGold(String userId, String friendId) {
        logger.info("偷金币前校验入参userId={}，friendId={}", userId, friendId);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            StageProperty DOG_HEAD = stagePropertyMapper.selectByType(StagePropertyTypeEnum.DOG_HEAD.getType());
            StageProperty DOG = stagePropertyMapper.selectByType(StagePropertyTypeEnum.DOG.getType());
            StageProperty TAI_DI = stagePropertyMapper.selectByType(StagePropertyTypeEnum.TAI_DI.getType());
            UserStageProperty record=new UserStageProperty();
            record.setUserId(Integer.parseInt(friendId));
            record.setStagePropertyId(DOG.getId());
            List<UserStageProperty> dogs=userStagePropertyMapper.selectByRecord(record);
            if(dogs!=null){
                UserStageProperty userStageProperty=dogs.get(0);
                if(userStageProperty.getCount()>0){
                    throw new BusinessException(ErrorCode.ACCOUNT_ERROR_313);
                }
            }
            UserStageProperty twoRecord=new UserStageProperty();
            twoRecord.setUserId(Integer.parseInt(friendId));
            twoRecord.setStagePropertyId(DOG_HEAD.getId());
            List<UserStageProperty> dogHeads=userStagePropertyMapper.selectByRecord(twoRecord);
            if(dogHeads!=null){
                UserStageProperty userStageProperty=dogHeads.get(0);
                if(userStageProperty.getCount()>0){
                    throw new BusinessException(ErrorCode.ACCOUNT_ERROR_313);
                }
            }

            UserStageProperty threeRecord=new UserStageProperty();
            threeRecord.setUserId(Integer.parseInt(friendId));
            threeRecord.setStagePropertyId(TAI_DI.getId());
            List<UserStageProperty> taiDis=userStagePropertyMapper.selectByRecord(twoRecord);
            if(taiDis!=null){
                UserStageProperty userStageProperty=taiDis.get(0);
                if(userStageProperty.getCount()>0){
                    throw new BusinessException(ErrorCode.ACCOUNT_ERROR_313);
                }
            }
        } catch (Exception e) {
            logger.error("偷金币前出现异常{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    public static void main(String[] args) {
        Random rand = new Random();
        int i = rand.nextInt(100); //int范围类的随机数
        i=i%2;
        System.out.println(i);
    }

    @Override
    @Transactional
    public ResultModel chandi(String userId, Integer seedId) {
        logger.info("铲地入参userId={}，seedId={}", userId, seedId);
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            UserField userField = userFieldMapper.selectByPrimaryKey(seedId);
            if (userField == null) {
                throw new BusinessException(ErrorCode.ACCOUNT_ERROR_314);
            }
            UserField update = new UserField();
            update.setId(seedId);
            update.setStatus(1);
            userFieldMapper.updateByPrimaryKeySelective(update);
        } catch (Exception e) {
            logger.error("使用道具出现异常{}", e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
}
